package com.neusoft.hifly.information.publish.service.impl;

import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.hifly.commons.database.DBUtil;
import com.neusoft.hifly.commons.database.SQLUtil;
import com.neusoft.hifly.commons.exception.SystemErrorException;
import com.neusoft.hifly.core.basic.service.impl.CTSaaSBaseServiceImpl;
import com.neusoft.hifly.core.log.Log;
import com.neusoft.hifly.core.utils.GlobalConstants;
import com.neusoft.hifly.core.utils.PublishUtils;
import com.neusoft.hifly.dynamicds.druid.DruidDBConfig;
import com.neusoft.hifly.information.publish.service.IReleaseService;
import com.neusoft.hifly.rpc.app.domain.DatasourceDTO;
import com.neusoft.hifly.rpc.app.service.IDatasourceService;

/**
 * Title: 文章资讯服务
 * <p>
 * Description: 发布 接口
 * <p>
 * Copyright: 2019
 * <p>
 * Company: 东软汉枫
 *
 * @author lh_neu
 * @version 1.0.0
 */
@Service
public class ReleaseServiceImpl extends CTSaaSBaseServiceImpl implements IReleaseService {

	@Autowired(required = false)
	private IDatasourceService datasourceService;
	@Autowired(required = false)
	private DruidDBConfig druidDBConfig;

	/**
	 * 发布
	 *
	 * @param organCode
	 *            租户编码
	 * @param datasourceLogicId
	 *            数据源逻辑ID
	 * @param isUpgrade
	 *            是否发布的升级脚本
	 * @throws SystemErrorException
	 *             自定义异常
	 */
	@Override
	public void release(final String organCode, final long datasourceLogicId, final boolean isUpgrade)
			throws SystemErrorException {
		if (StringUtils.isEmpty(organCode)) {
			return;
		}
		// 执行SQL语句
		final Map<String, String> replaceSqlMap = new HashMap<String, String>(2);
		// 租户编码
		replaceSqlMap.put(PublishUtils.TAB_ORGAN_CODE, StringUtils.upperCase(organCode));

		try {
			executeSQLScript(datasourceLogicId, PublishUtils.SQL_PATH, replaceSqlMap, null);
		} catch (final SystemErrorException e) {
			Log.error(e.getErrorDesc());
		}
	}

	/**
	 * 执行SQL语句
	 *
	 * @param datasourceLogicId
	 *            数据源逻辑ID
	 * @param dbFileSubPath
	 *            SQL脚本路径（相对的）
	 * @param replaceSqlMap
	 *            待替换的标签
	 * @param fileNamePrefix
	 *            文件名前缀
	 * @throws SystemErrorException
	 *             异常
	 */
	private void executeSQLScript(final long datasourceLogicId, final String dbFileSubPath,
			final Map<String, String> replaceSqlMap, final String fileNamePrefix) throws SystemErrorException {

		DatasourceDTO db = null;
		if (GlobalConstants.ABS_ID != datasourceLogicId) {
			db = datasourceService.getByLogicId(datasourceLogicId);
		}
		Connection conn = null;
		String dbType = null;
		if (db == null) {
			// 默认MySQL数据库
			dbType = SQLUtil.DB_MYSQL;

			try {
				conn = druidDBConfig.dataSource().getConnection();
			} catch (final SQLException e) {
				e.printStackTrace();
			}
		} else {
			dbType = db.getDbType();
			conn = connectDB(db);
		}
		//			if (StringUtils.isEmpty(db.getDbUrl()) || StringUtils.isEmpty(db.getDbType())
		//					|| StringUtils.isEmpty(db.getDbName())) {
		//				throw new SystemErrorException("数据库连接失败!无法执行SQL脚本");
		//			}
		//
		//			if (!ReleaseUtil.testConnDB(db)) {
		//				throw new SystemErrorException("数据库连接失败!无法执行SQL脚本");
		//			}

		final String dbFile = dbFileSubPath + File.separator
				+ (StringUtils.isNotEmpty(fileNamePrefix) ? fileNamePrefix : "") + PublishUtils.sqlFileName(dbType);

		// 执行脚本
		PublishUtils.runExecuteSQLScript(conn, dbFile, dbType, GlobalConstants.SYSTEM_UNCODE, replaceSqlMap, true,
				true);

	}

	/**
	 * 创建数据库连接
	 *
	 * @param db
	 *            数据源
	 * @return 连接
	 */
	private Connection connectDB(final DatasourceDTO db) {
		if (db == null) {
			return null;
		}
		return DBUtil.getInstanse().connection(db.getDbType(), db.getDbUrl(), db.getDbPort(), db.getDbName(),
				db.getDbCharacter(), db.getDbUser(), db.getDbPassword());
	}
}
